import api from '../../../api/index';
import common from '../../../common/index';

const app = getApp()

Page({
  data: {
    statusBarHeight: app.globalData.statusBarHeight,
    navBarHeight: app.globalData.navBarHeight,
    title: '',
    content: '',
    imageList: [] as string[],
    publishStatus: 'private',
    showDraftButton: false,
    pcenterPageShow: false,
    uid: ''
  },

  onLoad() {
    console.log('页面加载');
    const user = common.getAppUserInfo();
    this.setData({
      uid: user.uid
    });
    
    // 尝试加载最新的草稿
    this.loadLatestDraft();
  },

  onShow() {
    console.log('页面显示');
    // 页面显示时检查草稿按钮状态
    this.setData({
      showDraftButton: this.hasUnsavedContent()
    });
  },

  onHide() {
    // 页面隐藏时的处理
  },

  onUnload() {
    // 页面卸载时的处理
  },

  // 处理页面返回事件（系统返回键）
  onBackPress() {
    console.log('onBackPress被触发');
    // 检查是否有未保存内容
    if (this.hasUnsavedContent()) {
      // 有未保存内容，阻止默认返回行为，显示我们的提示
      console.log('有未保存内容，阻止默认返回');
      this.showSaveDraftModal();
      return true; // 返回true表示阻止默认返回行为
    }
    // 没有未保存内容，允许默认返回
    console.log('没有未保存内容，允许默认返回');
    return false;
  },

  // 检查是否有未保存的内容
  hasUnsavedContent() {
    const hasTitle = this.data.title.trim() !== '';
    const hasContent = this.data.content.trim() !== '';
    const hasImages = this.data.imageList.length > 0;
    
    return hasTitle || hasContent || hasImages;
  },

  // 加载最新的草稿
  loadLatestDraft() {
    try {
      const drafts = wx.getStorageSync('publish_drafts') || [];
      if (drafts.length > 0) {
        const latestDraft = drafts[0];
        console.log('找到最新草稿:', latestDraft);
        
        // 询问用户是否要恢复草稿
        wx.showModal({
          title: '发现草稿',
          content: '是否要恢复最新的草稿？',
          confirmText: '恢复草稿',
          cancelText: '新建内容',
          success: (res) => {
            if (res.confirm) {
              // 恢复草稿
              this.setData({
                title: latestDraft.title || '',
                content: latestDraft.content || '',
                imageList: latestDraft.imageList || [],
                publishStatus: latestDraft.publishStatus || 'private',
                showDraftButton: this.hasUnsavedContent()
              });
              
              wx.showToast({
                title: '草稿已恢复',
                icon: 'success'
              });
            }
          }
        });
      }
    } catch (error) {
      console.error('加载草稿失败:', error);
    }
  },

  // 返回方法
  goBack() {
    console.log('返回方法被调用');
    
    // 检查是否有未保存的内容
    const hasTitle = this.data.title.trim() !== '';
    const hasContent = this.data.content.trim() !== '';
    const hasImages = this.data.imageList.length > 0;
    
    if (hasTitle || hasContent || hasImages) {
      // 有未保存内容，提示保存草稿
      this.showSaveDraftModal();
    } else {
      // 没有输入任何内容，直接返回
      wx.navigateBack({
        delta: 1
      });
    }
  },

  // 显示保存草稿的模态框
  showSaveDraftModal() {
    const hasTitle = this.data.title.trim() !== '';
    const hasContent = this.data.content.trim() !== '';
    const hasImages = this.data.imageList.length > 0;
    
    // 构建提示内容
    let contentText = '您有未保存的内容：\n';
    if (hasTitle) contentText += '• 标题\n';
    if (hasContent) contentText += '• 正文\n';
    if (hasImages) contentText += '• 图片\n';
    contentText += '\n是否要保存为草稿？';
    
    wx.showModal({
      title: '保存草稿',
      content: contentText,
      confirmText: '保存草稿',
      cancelText: '直接离开',
      success: (res) => {
        if (res.confirm) {
          // 用户选择保存草稿
          this.saveAsDraft();
        } else {
          // 用户选择直接离开
          wx.navigateBack({
            delta: 1
          });
        }
      }
    });
  },

  // 显示个人中心
  showPcenterPage() {
    console.log('显示个人中心被调用');
    this.setData({
      pcenterPageShow: true
    });
  },

  // 关闭个人中心
  closePcenterPage() {
    this.setData({
      pcenterPageShow: false
    });
  },

  // 标题输入
  onTitleInput(e: any) {
    this.setData({
      title: e.detail.value,
      showDraftButton: this.hasUnsavedContent()
    });
  },

  // 内容输入
  onContentInput(e: any) {
    this.setData({
      content: e.detail.value,
      showDraftButton: this.hasUnsavedContent()
    });
  },

  // 选择图片
  chooseImage() {
    wx.chooseMedia({
      count: 9 - this.data.imageList.length,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFiles = res.tempFiles;
        const newImageList = [...this.data.imageList];
        
        tempFiles.forEach((file: any) => {
          if (file.tempFilePath) {
            newImageList.push(file.tempFilePath);
          }
        });
        
        this.setData({
          imageList: newImageList,
          showDraftButton: this.hasUnsavedContent()
        });
      }
    });
  },

  // 删除图片
  deleteImage(e: any) {
    const index = e.currentTarget.dataset.index;
    const imageList = [...this.data.imageList];
    imageList.splice(index, 1);
    this.setData({
      imageList,
      showDraftButton: this.hasUnsavedContent()
    });
  },

  // 预览图片
  previewImage(e: any) {
    const url = e.currentTarget.dataset.url;
    wx.previewImage({
      current: url,
      urls: this.data.imageList
    });
  },

  // 保存草稿
  saveAsDraft() {
    try {
      const draft = {
        title: this.data.title,
        content: this.data.content,
        imageList: this.data.imageList,
        publishStatus: this.data.publishStatus,
        createTime: new Date().toISOString()
      };
      
      const drafts = wx.getStorageSync('publish_drafts') || [];
      drafts.unshift(draft);
      
      if (drafts.length > 10) {
        drafts.splice(10);
      }
      
      wx.setStorageSync('publish_drafts', drafts);
      
      wx.showToast({
        title: '已保存为草稿',
        icon: 'success',
        duration: 1500
      });
      
      setTimeout(() => {
        wx.navigateBack({
          delta: 1
        });
      }, 1500);
      
    } catch (error) {
      console.error('保存草稿失败:', error);
      wx.showToast({
        title: '保存草稿失败',
        icon: 'error'
      });
    }
  },

  // 发布
  onPublish() {
    // 验证输入
    if (!this.data.title.trim()) {
      wx.showToast({
        title: '请输入标题',
        icon: 'none'
      });
      return;
    }

    if (!this.data.content.trim()) {
      wx.showToast({
        title: '请输入内容',
        icon: 'none'
      });
      return;
    }

    // 直接按当前选择的发布状态发布
    this.confirmPublish();
  },

  // 点击选择发布状态
  onSelectStatus(e: any) {
    const status = e.currentTarget.dataset.status;
    if (status === 'private' || status === 'public') {
      this.setData({ publishStatus: status });
    }
  },

  // 确认发布方法
  async confirmPublish() {
    wx.showLoading({
      title: '发布中...',
      mask: true
    });

    try {
      console.log('=== 调用发布接口 ===');
      const params = {
        uid: this.data.uid,
        title: this.data.title.trim(),
        content: this.data.content.trim(),
        image_url: this.data.imageList.length > 0 ? this.data.imageList[0] : '',
        status: this.data.publishStatus
      };
      
      console.log('发布参数:', params);
      
      const result = await api.publishInspiration(params);
      console.log('发布接口返回:', result);
      
      if ((result as any).status === 'success') {
        wx.hideLoading();
        wx.showToast({
          title: '发布成功',
          icon: 'success'
        });
        
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      } else {
        wx.hideLoading();
        wx.showToast({
          title: (result as any).message || '发布失败',
          icon: 'error'
        });
      }
    } catch (error) {
      wx.hideLoading();
      console.error('发布失败:', error);
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'error'
      });
    }
  }
});